<?php
namespace Guestbook\Controller;

use Guestbook\Model\MessageViewModel;
use Think\Controller;
use Think\Model;
use Think\Page;

class IndexController extends Controller {
    // 检测登录
    private function checkLogin()
    {
        if(!session('user.userId')){
            $this->error('请登录！', U('User/login'));
        }
    }
    // 留言列表
    public function index()
    {
        // MessageViewModel
        $model = new MessageViewModel();
        $count = $model->count();
        $p = getpage($count,4);
        // $page = new Page($count,4);
        $show = $p->show();
        $list = $model->order('messageId desc')->limit($p->firstRow.','.$p->listRows)->select();

        $this->assign('page',$show);
        $this->assign('list',$list);
        layout('Layout/layout');
        $this->display();
    }
    // 发表留言
    public function post()
    {
        $this->checkLogin();
        layout('Layout/layout');
        $this->display();
    }
    // 留言提交处理
    public function do_post()
    {
        $this->checkLogin();
        $content = I('content');
        if(empty($content)){
            $this->error('留言内容不能为空');
        }
        if(mb_strlen($content,'utf-8')>150){
            $this->error('留言内容最多150字');
        }
        $model = new Model('message');
        $userId = session('user.userId');
        $data = array(
            'content' => $content,
            'createdAt' => time(),
            'userId' => $userId
        );
        if(!($model->add($data))){
            $this->error('留言失败！');
        }else{
            $this->success('留言成功！',U('index'));

        }

    }
    // 删除留言
    public function delete()
    {
        $id = I('id');
        if(empty($id)){
            $this->error('缺少参数！');
        }
        $this->checkLogin();

        $model = new Model('message');
        $userId = session('user.userId');
        if(!$model->where(array('messageId'=>$id,'userId'=>$userId))->delete()){
            $this->error('删除失败！');
        }
        $this->success('删除成功！',U('index'));
    }
    
}